package com.hainatong.shiphelper.mainhome.viewmodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.blankj.utilcode.util.StringUtils;
import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.api.ApiService;
import com.hainatong.shiphelper.api.HttpResult;
import com.hainatong.shiphelper.api.VMObserver;
import com.hainatong.shiphelper.mainhome.entity.MsgBean;
import com.hainatong.shiphelper.mainhome.entity.WhereComBean;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.mvvmbase.base.BaseViewModel;
import com.hainatong.mvvmbase.base.PageLiveResult;
import com.hainatong.mvvmbase.http.RxSchedulersUtils;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.disposables.Disposable;

public class MsgViewModel extends BaseViewModel
{

    private int page;

    private boolean isRefresh = false;

    private boolean isHasNextPage = false;

    private String keyWord;

    private String userUuid;

    public MsgViewModel(@NonNull Application application)
    {
        super(application);
    }


    private MutableLiveData<PageLiveResult<List<MsgBean>>> msgListResult = new MutableLiveData<>();

    public MutableLiveData<PageLiveResult<List<MsgBean>>> getMsgListResult()
    {
        return msgListResult;
    }

    /**
     *  查询 系统 消息
     * @param
     */
    public void querySysMsg()
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        queryMsgListByParam( this.page,"",3 );
    }

    public void tryRefreshSysMsg()
    {
        querySysMsg();
    }

    public void loadMoreSysMsg()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryMsgListByParam(this.page,"",3);
        }
        else
        {
            PageLiveResult<List<MsgBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getMsgListResult().postValue(emptyResult);
        }
    }

    /**
     *  查询 各个 类型  消息列表
     *  msgType   1  预警 2 审批 3 系统 4 任务
     */
    private void queryMsgListByParam(int mPage,String userId,int msgType)
    {
        //{"wheres":"[{\"name\":\"dict_type\",\"value\":\"QSHe Type\"},{\"name\":\"dict_level\",\"value\":\"1\"}]","rows":"50","page":"1"}
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE, String.valueOf( mPage ));
        param.put( Constants.Key.ROWS, Constants.DEF_PAGE_SIZE);
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "type", String.valueOf( msgType ) ) );

        if( msgType == 2 || msgType == 1 || msgType == 4 )
        {
            if(!StringUtils.isEmpty( userId ))
            {
                whereList.add( new WhereComBean( "user_id", userId ) );
            }
        }

        param.put( "wheres", GsonUtil.obj2json( whereList ));

        ApiService.Builder.getChanBoServer()
                          .getSysMsgList(param)
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<HttpResult<List<MsgBean>>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                 addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  PageLiveResult<List<MsgBean>> errorResult = new PageLiveResult<>();
                                  errorResult.setSuccess(false);
                                  errorResult.setRefresh(isRefresh);
                                  errorResult.setMsg(errorMsg);
                                  if( !isRefresh )
                                  {
                                      errorResult.setLoadMoreEmpty(true);
                                  }
                                  getMsgListResult().postValue( errorResult );
                              }

                              @Override
                              public void onSuccess(HttpResult<List<MsgBean>> result)
                              {
                                  if( result.isOk() )
                                  {
                                      PageLiveResult<List<MsgBean>> listResult = new PageLiveResult<>();
                                      listResult.setSuccess(true);
                                      listResult.setRefresh(isRefresh);
                                      if( result.getRows() != null && !result.getRows().isEmpty() )
                                      {
                                          listResult.setData( result.getRows() );
                                          if( result.getRows().size() < Constants.DEF_PAGE_SIZE )
                                          {
                                              isHasNextPage = false;
                                          }
                                          else
                                          {
                                              isHasNextPage = true;
                                              page = page + 1;
                                          }
                                      }
                                      getMsgListResult().postValue(listResult);
                                  }
                                  else
                                  {
                                      PageLiveResult<List<MsgBean>> failResult = new PageLiveResult<>();
                                      failResult.setSuccess(false);
                                      failResult.setRefresh(isRefresh);
                                      failResult.setMsg(result.getMsg());
                                      if( !isRefresh )
                                      {
                                          failResult.setLoadMoreEmpty(true);
                                      }
                                      getMsgListResult().postValue(failResult);
                                  }
                              }
                          });

    }


    /**
     *  查询 审批消息
     * @param userId
     */
    public void queryShenPiMsgByUserID( String userId )
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        this.userUuid = userId;
         queryMsgListByParam( this.page,userId,2 );
    }

    public void tryRefreshShenPiMs()
    {
        queryShenPiMsgByUserID(this.userUuid);
    }

    public void loadMoreShenPiMs()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryMsgListByParam(this.page,this.userUuid,2);
        }
        else
        {
            PageLiveResult<List<MsgBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getMsgListResult().postValue(emptyResult);
        }
    }

    /**
     *  查询 预警 消息
      */
   public void queryWarnMsg(String userId)
   {
       this.page = 1;
       this.isRefresh = true;
       this.isHasNextPage = true;
       this.userUuid = userId;
       queryMsgListByParam( this.page,"",1 );

   }

    public void tryRefreshWarnMsg()
    {
        queryWarnMsg(this.userUuid);
    }

    public void loadMoreWarnMsg()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryMsgListByParam(this.page,this.userUuid,1);
        }
        else
        {
            PageLiveResult<List<MsgBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getMsgListResult().postValue(emptyResult);
        }
    }


    /**
     *  查询任务消息
     * @param userId
     */
    public void queryTaskMsgByUserId(String userId)
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        this.userUuid = userId;
        queryMsgListByParam( this.page,this.userUuid,4 );

    }

    public void tryRefreshTaskMsg()
    {
        queryTaskMsgByUserId(this.userUuid);
    }

    public void loadMoreTaskMsg()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryMsgListByParam(this.page,this.userUuid,4);
        }
        else
        {
            PageLiveResult<List<MsgBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getMsgListResult().postValue(emptyResult);
        }
    }



    //int mPage,String userId,int msgType
    public void queryMsgList()
    {
        this.isRefresh = true;
        this.isHasNextPage = true;

        //{"wheres":"[{\"name\":\"dict_type\",\"value\":\"QSHe Type\"},{\"name\":\"dict_level\",\"value\":\"1\"}]","rows":"50","page":"1"}
        Map<String,Object> param = new HashMap<String,Object>();
        //String.valueOf( mPage )
        param.put(Constants.Key.PAGE, "1" );
        param.put( Constants.Key.ROWS, Constants.DEF_PAGE_SIZE);
        List<WhereComBean> whereList = new ArrayList<>();
        //whereList.add( new WhereComBean( "type", String.valueOf( msgType ) ) );

        //param.put( "wheres", GsonUtil.obj2json( whereList ));

        ApiService.Builder.getChanBoServer()
                .getSysMsgList(param)
                .compose( RxSchedulersUtils.Obs_io_main() )
                .subscribe(new VMObserver<HttpResult<List<MsgBean>>>()
                {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        PageLiveResult<List<MsgBean>> errorResult = new PageLiveResult<>();
                        errorResult.setSuccess(false);
                        errorResult.setRefresh(isRefresh);
                        errorResult.setMsg(errorMsg);
                        if( !isRefresh )
                        {
                            errorResult.setLoadMoreEmpty(true);
                        }
                        getMsgListResult().postValue( errorResult );
                    }

                    @Override
                    public void onSuccess(HttpResult<List<MsgBean>> result)
                    {
                        if( result.isOk() )
                        {
                            PageLiveResult<List<MsgBean>> listResult = new PageLiveResult<>();
                            listResult.setSuccess(true);
                            listResult.setRefresh(isRefresh);
                            if( result.getRows() != null && !result.getRows().isEmpty() )
                            {
                                listResult.setData( result.getRows() );
                                if( result.getRows().size() < Constants.DEF_PAGE_SIZE )
                                {
                                    isHasNextPage = false;
                                }
                                else
                                {
                                    isHasNextPage = true;
                                    page = page + 1;
                                }
                            }
                            getMsgListResult().postValue(listResult);
                        }
                        else
                        {
                            PageLiveResult<List<MsgBean>> failResult = new PageLiveResult<>();
                            failResult.setSuccess(false);
                            failResult.setRefresh(isRefresh);
                            failResult.setMsg(result.getMsg());
                            if( !isRefresh )
                            {
                                failResult.setLoadMoreEmpty(true);
                            }
                            getMsgListResult().postValue(failResult);
                        }
                    }
                });

    }




}
